"""This module has components that are used for testing tuya's device control and Pulsar massage queue."""
import logging
from tuya_connector import (
    TuyaOpenAPI,
    TuyaOpenPulsar,
    TuyaCloudPulsarTopic,
    TUYA_LOGGER,
)

import uvicorn
import json
import os

from fastapi import FastAPI
from fastapi import Response
from example.message import MessageBody

gunicorn_logger = logging.getLogger('gunicorn.error')

app = FastAPI()

ACCESS_ID = "p8jewd3ra9trfkx8p1jg"
ACCESS_KEY = "eb148813e3984a63a9a5552fb24258f6"
API_ENDPOINT = "https://openapi.tuyacn.com"
MQ_ENDPOINT = "wss://mqe.tuyacn.com:8285/"

# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)

# Init openapi and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()


# Call any API from Tuya
# set up device_id
# DEVICE_ID = "6c1cb16c8477a6c4ce6fzv"

# Call API from Tuya
# Get the device information
# response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))
#
# #Get the instruction set of the device
# response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))

# Send commands
# commands = {'commands': [{'code': 'switch_led', 'value': True}]}
# openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)


# openapi.get('/v1.0/iot-03/devices', {"size": 10})

# Get the status of a single device
# response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))

# # Init Message Queue
# open_pulsar = TuyaOpenPulsar(
#     ACCESS_ID, ACCESS_KEY, MQ_ENDPOINT, TuyaCloudPulsarTopic.PROD
# )
# # Add Message Queue listener
# open_pulsar.add_message_listener(lambda msg: print(f"---\nexample receive: {msg}"))
#
# # Start Message Queue
# open_pulsar.start()
#
# input()
# # Stop Message Queue
# open_pulsar.stop()

def key(room: str, model: str):
    return f"{room}_{model}"


def load_models():
    models_dir = 'models'
    if not os.path.exists(models_dir):
        models_dir = 'example/models'
    result = {}
    for room_file in os.listdir(models_dir):
        room = room_file.replace('.txt', '')
        with open(os.path.join(models_dir, room_file)) as f:
            models = json.load(f)
            for model in models.keys():
                result[key(room, model)] = models[model]
    return result


cmd_models = load_models()
print(cmd_models)
print(cmd_models.keys())


def find_model(room: str, model: str):
    cmd_key = key(room, model)
    if not room:
        for k in cmd_models.keys():
            if model in k:
                cmd_key = k
                break

    return cmd_models.get(cmd_key, [])


@app.get("/get_models/keys")
def get_models():
    return {"models": list(cmd_models.keys())}


# room可以为空，room为空只判断model
@app.post("/")
async def home_post(body: MessageBody):
    model = find_model(body.room, body.model)
    if model:
        results = []
        for cmd in model:
            commands = {'commands': cmd.get('commands', [])}
            device_id = cmd.get('deviceId', '')
            response = openapi.post('/v1.0/iot-03/devices/{}/commands'.format(device_id), commands)
            results.append(response)
        return {
            "Code": 200,
            "Success": True,
            "Message": "请求成功",
            "results": results
        }
    else:
        return {
            "Code": 200,
            "Success": False,
            "Message": f"没有找到模式:{body.model}"
        }


if __name__ == "__main__":
    uvicorn.run("main:app")
